package com.ff.neuropp.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.ff.neuropp.domain.Resource;
import com.ff.neuropp.repository.ResourceRepository;
import com.ff.neuropp.util.SpecificationUtil;

/**
 * Resource 信息
 */
@Service
public class ResourceService {

	@Autowired
    private ResourceRepository resourceRepository;
	
	public Resource saveResource(Resource resource) {
		return resourceRepository.save(resource);
	}

	public Resource findById(int id) {
		 Optional<Resource> optional = resourceRepository.findById(id);
	        if (optional.isPresent()) {
	            return optional.get();
	        } else {
	            return null;
	        }
	}

	public Page<Resource> findPage(@Valid Resource resource) {
		  Map<String, Object> sqlParams = new HashMap<>();
	        if (null == resource.getPageNo()) {
	        	resource.setPageNo(1);
	        } else if (resource.getPageNo() < 1) {
	        	resource.setPageNo(1);
	        }
	        if (null == resource.getPageSize()) {
	        	resource.setPageSize(10);
	        }
	        sqlParams.put("GT_id",0);
	        if(null !=resource.getSearch() && resource.getSearch().trim().length()>0){
	            sqlParams.put("LIKE_name",resource.getSearch());
	        }

	        Sort.Direction direction = Sort.Direction.DESC;
	        String sort = "id";
	        Pageable pageable = new PageRequest(resource.getPageNo()-1,resource.getPageSize(), direction, sort);
	        return resourceRepository.findAll(SpecificationUtil.buildSpecification(sqlParams, Resource.class), pageable);
	}

    /**
     * 根据id 删除实体
     * @param id
     */
	public void deleteById(Integer id) {
		resourceRepository.deleteById(id);
	}


}
